import { _decorator, Component, Tween, tween, Vec2, Node, Vec3, UIOpacity } from "cc";

const { ccclass, property } = _decorator;

@ccclass('GuidedSlide')
export class GuidedSlide extends Component {
    private _startPos: Vec3 = null!;
    private _targetPos: Vec3 = null!;
    private _interval: number = 2;
    private _tween: Tween<Node> = null!;

    public init(startPos: Vec3, targetPos: Vec3, interval: number = 2) {
        this._startPos = startPos;
        this._targetPos = targetPos;
        this._interval = interval;

        // 设置初始位置
        this.node.position = this._startPos;

        tween(this.node.getComponent(UIOpacity))
            .to(0.5, { opacity: 255 })
            .call(this.startSlideAnim.bind(this))
            .start();
    }

    private startSlideAnim() {
        // 停止之前的动画
        if (this._tween) {
            this._tween.stop();
        }

        this.node.getComponent(UIOpacity).opacity = 255;

        // 创建新的动画
        this._tween = tween(this.node)
            .to(1.1, { position: this._targetPos }, {
                easing: 'cubicOut',
                onComplete: () => {
                    // 延迟后重置位置并重新开始
                    this.scheduleOnce(() => {
                        this.node.position = this._startPos;
                        this.startSlideAnim();
                    }, this._interval);
                }
            })
            .start();

        tween(this.node.getComponent(UIOpacity))
            .to(1, { opacity: 0 }).start();
    }

    onDestroy() {
        if (this._tween) {
            this._tween.stop();
        }
        this.unscheduleAllCallbacks();
    }
}

